package com.smp.handler;

import com.smp.common.BaseVo;
import com.smp.common.ResultCode;
import com.smp.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.ResourceAccessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: xiaoyu
 * @date: 2020/4/24 ,13:31
 * @version: v1.0
 * @description: 业务异常，参数校验异常等拦截
 **/
@Slf4j
@Component
@ControllerAdvice
public class ErrorHandler {

    /**
     * 业务异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleBindException(BusinessException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.WRONG.getCode(), ex.getMessage());
    }

    /**
     * restTemplate的异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ResourceAccessException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleBindResourceAccessException(ResourceAccessException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.WRONG.getCode(), ex.getMessage());
    }

    /**
     * 参数验证、绑定异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseVo handleValidateException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.ERR_CHECK_PARAM.getCode(), ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 控制层参数校验
     *
     * @param ex
     * @param req
     * @param res
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleAllException(Throwable ex, HttpServletRequest req, HttpServletResponse res) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.WRONG.getCode(), ResultCode.WRONG.getInfo());
    }

    /**
     * 绑定异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleBindException(BindException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.PARAMETER_ERROR.getCode(), ex.getFieldError().getDefaultMessage());
    }

}
